//
//  JMProfileViewController.m
//  OpenSesame
//
//  Created by zhangjiaming on 15/12/21.
//  Copyright © 2015年 OpenSesame. All rights reserved.
//

#import "JMProfileViewController.h"
#import "JMProfileCell.h"
#import "JMOperateController.h"
#import "JMUpdateController.h"
#import "JMOpinionController.h"
#import "JMAccountSafeController.h"
#import "JMAboutUsController.h"
#import "JMLoginViewController.h"
#import "JMWebViewController.h"
#import "JMUserAccountTool.h"
#import "MBProgressHUD+JM.h"
#import "JMUserAccountTool.h"
#import "JMUploadIconTool.h"
#import "UIButton+WebCache.h"
// 修改头像
#define PhotoUpdate @"http://47.92.139.238/copying/user/photoUpdate"
// 获取用户信息
#define UserInfo @"http://47.92.139.238/copying/user/userInfo"
@interface JMProfileViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backImageView;
@property (strong, nonatomic) NSArray *pictureNameArray;
@property (strong, nonatomic) NSArray *textArray;
@property (weak, nonatomic) UITextField *nameField;
@property (weak, nonatomic) UITextField *signalField;

@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (weak, nonatomic) UIButton *iconBtn;
@end

@implementation JMProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 隐藏导航条
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = JMColor(242, 242, 242);
    
    // 设置界面
   // [self setUpInterface];
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self setUpInterface];
}
/**
 *  设置界面
 */
- (void)setUpInterface {
    NSUserDefaults *defult =[NSUserDefaults standardUserDefaults];
    NSLog(@"%@",[defult objectForKey:@"token"]);
    [JMHttpTool post:UserInfo param:@{@"token":[defult objectForKey:@"token"]} success:^(id responseObject) {
        NSDictionary *dic =[NSDictionary dictionaryWithDictionary:responseObject];
        NSString *imageStr =[NSString stringWithFormat:@"%@%@",@"http://47.92.139.238/",dic[@"data"][@"photo"]];
        UIButton *icon = [[UIButton alloc] init];
        [self.view addSubview:icon];
        
        
        UIImage *iconImage = [UIImage imageWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"icon.png"]];
        
            if (iconImage) {
                [icon setImage:iconImage forState:UIControlStateNormal];
            } else {
                
            //  [icon sd_setImageWithURL:[NSURL URLWithString:imageStr] forState:UIControlStateNormal];
                [icon sd_setImageWithURL:[NSURL URLWithString:imageStr] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"头像"]];
            }
        
        icon.width = 90;
        icon.height = 90;
        icon.x = (JMPhoneWidth - 90) * 0.5;
        icon.y = 30;
        [icon.layer setMasksToBounds:YES];
        [icon.layer setCornerRadius:45.0];
        [icon addTarget:self action:@selector(selecteImage) forControlEvents:UIControlEventTouchUpInside];
        self.iconBtn = icon;
        // 设置用户名label
        UITextField *namelabel = [[UITextField alloc] init];
        namelabel.tag = 1;
        namelabel.clearsOnBeginEditing = YES;
        self.nameField = namelabel;
        namelabel.delegate = self;
        namelabel.returnKeyType = UIReturnKeyDone;
        [self.view addSubview:namelabel];
        namelabel.width = 200;
        namelabel.height = 16;
        [namelabel setFont:[UIFont systemFontOfSize:16]];
        namelabel.x = (JMPhoneWidth - namelabel.width) * 0.5;
        namelabel.y = icon.y + icon.height + 15;
        namelabel.textColor = [UIColor whiteColor];
        namelabel.textAlignment = NSTextAlignmentCenter;
       // if (account.Name) {
       //     namelabel.text = account.Name;
      //  } else {
            namelabel.text = @"锁大叔";
     //   }
        
        // 设置签名label
        UITextField *signlabel = [[UITextField alloc] init];
        signlabel.tag = 2;
        self.signalField = signlabel;
        signlabel.returnKeyType = UIReturnKeyDone;
        signlabel.delegate = self;
        [self.view addSubview:signlabel];
        signlabel.width = JMPhoneWidth;
        signlabel.height = 13;
        signlabel.x = 0;
        signlabel.y = namelabel.y + namelabel.height + 10;
        [signlabel setFont:[UIFont systemFontOfSize:13]];
        signlabel.textColor = [UIColor whiteColor];
        signlabel.textAlignment = NSTextAlignmentCenter;
      //  if (account.Des) {
       //     signlabel.text = account.Des;
      //  } else {
            signlabel.text = @"专业开锁二十年无敌手，耶~";
     //   }

    } frail:^(NSError *error) {
        
    }];
//    // 获取账户信息
//    JMUserAccount *account = [JMUserAccountTool account];
//    
//    // 设置头像
//    UIButton *icon = [[UIButton alloc] init];
//    [self.view addSubview:icon];
//    UIImage *iconImage = [UIImage imageWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"icon.png"]];
//
//    if (iconImage) {
//        [icon setImage:iconImage forState:UIControlStateNormal];
//        //[icon setImage:iconImage forState:UIControlStateHighlighted];
//    } else {
//        [icon setImage:[UIImage imageNamed:@"头像"] forState:UIControlStateNormal];
//        //[icon setImage:[UIImage imageNamed:@"头像"] forState:UIControlStateHighlighted];
//    }
//    
//    icon.width = 90;
//    icon.height = 90;
//    icon.x = (JMPhoneWidth - 90) * 0.5;
//    icon.y = 30;
//    [icon.layer setMasksToBounds:YES];
//    [icon.layer setCornerRadius:45.0];
//    [icon addTarget:self action:@selector(selecteImage) forControlEvents:UIControlEventTouchUpInside];
//    self.iconBtn = icon;
//    
//    // 设置用户名label
//    UITextField *namelabel = [[UITextField alloc] init];
//    namelabel.tag = 1;
//    namelabel.clearsOnBeginEditing = YES;
//    self.nameField = namelabel;
//    namelabel.delegate = self;
//    namelabel.returnKeyType = UIReturnKeyDone;
//    [self.view addSubview:namelabel];
//    namelabel.width = 200;
//    namelabel.height = 16;
//    [namelabel setFont:[UIFont systemFontOfSize:16]];
//    namelabel.x = (JMPhoneWidth - namelabel.width) * 0.5;
//    namelabel.y = icon.y + icon.height + 15;
//    namelabel.textColor = [UIColor whiteColor];
//    namelabel.textAlignment = NSTextAlignmentCenter;
//    if (account.Name) {
//        namelabel.text = account.Name;
//    } else {
//        namelabel.text = @"锁大叔";
//    }
//    
//    // 设置签名label
//    UITextField *signlabel = [[UITextField alloc] init];
//    signlabel.tag = 2;
//    self.signalField = signlabel;
//    signlabel.returnKeyType = UIReturnKeyDone;
//    signlabel.delegate = self;
//    [self.view addSubview:signlabel];
//    signlabel.width = JMPhoneWidth;
//    signlabel.height = 13;
//    signlabel.x = 0;
//    signlabel.y = namelabel.y + namelabel.height + 10;
//    [signlabel setFont:[UIFont systemFontOfSize:13]];
//    signlabel.textColor = [UIColor whiteColor];
//    signlabel.textAlignment = NSTextAlignmentCenter;
//    if (account.Des) {
//        signlabel.text = account.Des;
//    } else {
//       signlabel.text = @"专业开锁二十年无敌手，耶~";
//    }
    
    // 设置下面的tableView
    UITableView *tableView = [[UITableView alloc] init];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:tableView];
    CGFloat tableViewH = 0;
    if (JMPhoneHeight - 205 - 49 < 357) { // 不能显示完tableview
        tableViewH = JMPhoneHeight - 205 - 49;
        tableView.contentSize = CGSizeMake(0, 357 -  tableViewH);
    } else { // 能显示完tableview
        tableViewH = 357;
    }
    tableView.frame = CGRectMake(0, 205, JMPhoneWidth, tableViewH);
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.bounces = NO;
    
    NSString *image1 = @"硬件升级";
    NSString *image2 = @"帮助与反馈";
    NSString *image3 = @"帐号与安全";
    NSString *image4 = @"关于我们";
    NSString *image5 = @"微信平台";
    NSString *image6 = @"网站平台";
    NSString *image7 = @"退出";
    NSArray *pictureNameArray = [NSArray arrayWithObjects:image1, image2, image3, image4, image5, image6, image7, nil];
    self.pictureNameArray = pictureNameArray;
    
    NSString *text1 = @"硬件更新";
    NSString *text2 = @"帮助与反馈";
    NSString *text3 = @"账号与安全";
    NSString *text4 = @"关于我们";
    NSString *text5 = @"微信平台";
    NSString *text6 = @"网站平台";
    NSString *text7 = @"退出";
    NSArray *textArray = [NSArray arrayWithObjects:text1, text2, text3, text4, text5, text6, text7, nil];
    self.textArray = textArray;
    
    // 监听用户名的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountDidChange) name:@"accountDidChange" object:nil];
}

/** 监听会员名称的改变 */
- (void)accountDidChange {
    JMUserAccount *account = [JMUserAccountTool account];
    self.nameField.text = account.Name;
}

/**
 *  选择照片
 */
- (void)selecteImage {

    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    [sheet addButtonWithTitle:@"从相册选取"];
    [sheet addButtonWithTitle:@"拍照选取"];
    sheet.frame = CGRectMake(JMPhoneWidth * 0.5, JMPhoneHeight * 0.5, 70, 70);
    [sheet showInView:self.view];
}

/**
 *  从相册或拍照选取图片
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (1 == buttonIndex) { // 从相册选取
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        _imagePicker.delegate = (id)self;
        _imagePicker.allowsEditing = YES;
        _imagePicker.navigationBar.tintColor = [UIColor whiteColor];
        [self presentViewController:_imagePicker animated:YES completion:nil];
    } else if(2 == buttonIndex) { // 相机拍照
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePicker.delegate = (id)self;
        _imagePicker.allowsEditing = YES;
        _imagePicker.navigationBar.tintColor = [UIColor whiteColor];
        [self presentViewController:_imagePicker animated:YES completion:nil];
    }
}

/**
 *  展示并保存选择的图片
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image= info[UIImagePickerControllerEditedImage];
   // UIImage *image =  [UIImage scaleImage:image1 toScale:0.3];
    [self.iconBtn setImage:image forState:UIControlStateNormal];
    
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *dataStr =[NSString stringWithFormat:@"%@",[imageData base64EncodedStringWithOptions:0]];
   // NSData *dataStr = [[NSData alloc]initWithBase64EncodedData:imageData options:0];
    [self photoUpdate:dataStr];
 /*
    // 获取用户信息
    JMUserAccount *account = [JMUserAccountTool account];
    
    // 设置请求参数
    JMUploadIconParam *param = [[JMUploadIconParam alloc] init];
    param.Method = @"USER_CHANGE_HEAD";
    param.ID = account.ID;
    
    // 设置上传数据
    NSData *imageData = UIImageJPEGRepresentation(image, 0.001);
    
    // 设置服务器接收文件参数名称
    NSString *name = @"file";
    
    // 设置文件名称
    NSString *fileName = @"icon";
    
    // 设置上传的文件类型
    NSString *mimeType = @"image/jpeg";
    [JMUploadIconTool uploadIconWithParameter:param data:imageData servicerParamName:name fileName:fileName mimeType:mimeType success:^(JMUploadIconResult *result) {
        if (0 == result.Result) { // 成功
        }
    } failure:^(NSError *error) {
    }];
   */
    // 异步存储图片到沙盒
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"icon.png"];
        [UIImageJPEGRepresentation(image, 0.5)writeToFile:path atomically:YES];
    });
}

-(void)photoUpdate:(NSString *)dataStr{
    NSUserDefaults *defult = [NSUserDefaults standardUserDefaults];
    NSLog(@"%@",[defult objectForKey:@"token"]);
    NSDictionary *dic = @{@"token":[defult objectForKey:@"token"],
                          @"photo":dataStr
                          };
    [JMHttpTool post:PhotoUpdate param:dic success:^(id responseObject) {
        NSDictionary *dict =[NSDictionary dictionaryWithDictionary:responseObject];
        if ([dict[@"code"]  isEqualToString:@"200"]) {
            [MBProgressHUD showSuccess:@"头像上传成功"];
           // [self viewWillAppear:YES];
        }
        
    } frail:^(NSError *error) {
        
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableView数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.textArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JMProfileCell *cell = [JMProfileCell cellWithTableView:tableView];
    NSString *imageName = self.pictureNameArray[indexPath.row];
    NSString *text = self.textArray[indexPath.row];
    cell.picture.image = [UIImage imageNamed:imageName];
    cell.label.text = text;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 51;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.navigationController.navigationBar.hidden = NO;
    // 返回时cell没有了背景颜色
    [tableView reloadData];
    if (0 == indexPath.row) { // 硬件跟新
        JMUpdateController *updateVC = [[JMUpdateController alloc] init];
        [self.navigationController pushViewController:updateVC animated:YES];
    } else if (1 == indexPath.row) { // 帮助与反馈
        JMOpinionController *opinionVC = [[JMOpinionController alloc] init];
        [self.navigationController pushViewController:opinionVC animated:YES];
    } else if (2 == indexPath.row) { // 账号与安全
        JMAccountSafeController *account = [[JMAccountSafeController alloc] init];
        [self.navigationController pushViewController:account animated:YES];
    } else if (3 == indexPath.row) { // 关于我们
        JMAboutUsController *aboutVC = [[JMAboutUsController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
    } else if (4 == indexPath.row) { // 微信平台
        JMAboutUsController *aboutVC = [[JMAboutUsController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
    } else if (5 == indexPath.row) { // 网站平台
        JMWebViewController *webVC = [[JMWebViewController alloc] init];
        [self.navigationController pushViewController:webVC animated:YES];
    } else if (6 == indexPath.row) { // 退出
        // 删除用户保存的密码
        JMUserAccount *account = [JMUserAccountTool account];
        account.Token = nil;
        account.Name = nil;
        [JMUserAccountTool saveAccount:account];
        
        self.navigationController.navigationBar.hidden = YES;
        JMLoginViewController *loginVC = [[JMLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

/** 监听会员名的更改，向服务器发送请求 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // 获取用户信息
    JMUserAccount *account = [JMUserAccountTool account];
    
    // 获取时间戳
    NSString *timeStamp = [NSDate timeStamp];
    if (textField.tag == 1) { // 修改用户名
    
        if ([string isEqualToString:@"\n"]) {
            // 设置请求参数
            NSMutableArray *params = [[NSMutableArray alloc] initWithObjects:@"USER_CHANGE_NAME",@"ID",account.ID,@"Newname",textField.text,@"Time",timeStamp,@"Token",account.Token, nil];
            // 发送请求
            [JMHttpTool requestWithParameter:params success:^(JMParam *result) {
                [MBProgressHUD hideHUD];
                if ([result.Result isEqualToString:@"0"]) { // 成功
                    account.Name = textField.text;
                    [JMUserAccountTool saveAccount:account];
                    self.nameField.text = textField.text;
                    [MBProgressHUD showSuccess:@"修改成功"];
                } else if ([result.Result isEqualToString:@"1"]) { // 服务器出错
                    [MBProgressHUD showError:@"服务器出错"];
                } else if ([result.Result isEqualToString:@"2"]) { // 格式不正确
                    [MBProgressHUD showError:@"用户名格式不正确"];
                }
                
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"请检查您的网络"];
            }];
            
            [textField resignFirstResponder];
            return YES;
        }

    } else if (textField.tag == 2) { // 修改个人介绍
        if ([string isEqualToString:@"\n"]) {
            // 设置请求参数
            NSMutableArray *params = [[NSMutableArray alloc] initWithObjects:@"USER_CHANGE_DES",@"ID",account.ID,@"Newdes",[textField.text deleateOccurrencesOfStringArray:@[@" "]],@"Time",timeStamp,@"Token",account.Token, nil];
            // 发送请求
            [JMHttpTool requestWithParameter:params success:^(JMParam *result) {
                [MBProgressHUD hideHUD];
                if ([result.Result isEqualToString:@"0"]) { // 成功
                    self.signalField.text = textField.text;
                    account.Des = textField.text;
                    [JMUserAccountTool saveAccount:account];
                    [MBProgressHUD showSuccess:@"修改成功"];
                } else if ([result.Result isEqualToString:@"1"]) { // 服务器出错
                    [MBProgressHUD showError:@"服务器出错"];
                } else if ([result.Result isEqualToString:@"2"]) { // 格式不正确
                    [MBProgressHUD showError:@"格式不正确"];
                }
                
            } failure:^(NSError *error) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"请检查您的网络"];
            }];

            [textField resignFirstResponder];
            return YES;
        }
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.nameField resignFirstResponder];
    [self.signalField resignFirstResponder];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
